# !/usr/bin/python
# -*- coding:utf-8 -*-
"""
pip install pymongo
@author:zhuyan7
@file: configutil.py
@time: 2018/08/23
"""


import MySQLdb
from file.log import Log
import traceback
from bson.objectid import ObjectId
import datetime

log = Log().getLog()


class MysqlUtil:

    def __init__(self, db_file):
        cfg = DbConfig(db_file, model_name="mysql")
        self.db = MySQLdb.connect(host=cfg.host, port=cfg.port, user=cfg.user, passwd=cfg.password, db=cfg.db_name)

    def close(self):
        self.db.close()

    def find_one(self, sql):
        """
        返回单条记录
        :param sql:
        :return:
        """
        log.info(u"执行sql为：%s", sql)
        cursor = self.db.cursor()
        dict_data = {}
        try:
            cursor.execute(sql)
            data = cursor.fetchone()
            dict_data[cursor.description[0][0]] = data[0]
            log.info(u"返回的数据结果为：%s", data)
        except Exception as e:
            traceback.extract_stack()
            log.info(u'执行sql报错',e)
        finally:
            self.db.close()
        return dict_data

    def find(self, sql):
        """
        返回多条记录
        :param sql:
        :return:
        """
        log.info(u"执行sql为：%s", sql)
        cursor = self.db.cursor()
        dict_data = {}
        try:
            cursor.execute(sql)
            data = cursor.fetchall()
            col_size = len(cursor.description)
            for row in data:
                for j in range(col_size):
                    dict_data[cursor.description[j][0]] = row[j]
            log.info(u"返回的数据结果为：%s", data)
        except Exception as e:
            log.error(u'执行sql报错',e)
        finally:
            self.db.close()
        return dict_data


class DbConfig:

    def __init__(self, db_file, model_name):
        config_util = ConfigUtil()
        config_util.read_config(db_file)
        self.__host = config_util.get_opt_value(model_name, model_name+".host")
        self.__driver = config_util.get_opt_value(model_name, model_name + ".driver")
        self.__port = config_util.get_opt_value(model_name, model_name+".port")
        self.__user = config_util.get_opt_value(model_name, model_name+".user")
        self.__password = config_util.get_opt_value(model_name, model_name+".pwd")
        self.__db_name = config_util.get_opt_value(model_name, model_name+".dbName")

    @property
    def host(self):
        return self.__host

    @property
    def port(self):
        return int(self.__port)

    @property
    def user(self):
        return self.__user

    @property
    def password(self):
        return self.__password

    @property
    def db_name(self):
        return self.__db_name

    @property
    def driver(self):
        return self.__driver


if __name__ == '__main__':
    util = MysqlUtil("db.cfg")
    sql = "select * from jtalk_cs_status t where t.user_id='110010000000115282'"
    print util.find(sql)






